home *** CD-ROM | disk | FTP | other *** search
/ Acorn User: China / Acorn User China CD-ROM (UK) (Disc B) / Acorn User China CD-ROM (UK) (Disc B).bin / STUTTGART / LANG / GOFER / !Gofer_preludes_gcwprel < prev    next >
Encoding:
Text File  |  1993-11-22  |  31.3 KB  |  1,009 lines

  1. --         __________   __________   __________   __________   ________
  2. --        /  _______/  /  ____   /  /  _______/  /  _______/  /  ____  \
  3. --       /  / _____   /  /   /  /  /  /______   /  /______   /  /___/  /
  4. --      /  / /_   /  /  /   /  /  /  _______/  /  _______/  /  __   __/
  5. --     /  /___/  /  /  /___/  /  /  /         /  /______   /  /  \  \ 
  6. --    /_________/  /_________/  /__/         /_________/  /__/    \__\
  7. --
  8. --    Functional programming environment, Version 2.28
  9. --    Copyright Mark P Jones 1991-1993.
  10. --
  11. --    Gavin's prelude for use of overloading with constructor classes.
  12. --    Based on the Haskell standard prelude version 1.2.
  13.  
  14. help = "press :? for a list of commands"
  15.  
  16. -- Operator precedence table: ---------------------------------------------
  17.  
  18. infixl 9 !!
  19. infixr 9 ., @@
  20. infixr 8 ^
  21. infixl 7 *
  22. infix  7 /, `div`, `quot`, `rem`, `mod`
  23. infixl 6 +, -
  24. infix  5 \\
  25. infixr 5 ++, :
  26. infix  4 ==, /=, <, <=, >=, >
  27. infix  4 `elem`, `notElem`
  28. infixr 3 &&
  29. infixr 2 ||
  30. infixr 0 $
  31.  
  32. -- Standard combinators: -------------------------------------------------
  33.  
  34. primitive strict "primStrict" :: (a -> b) -> a -> b
  35.  
  36. const          :: a -> b -> a
  37. const k x       = k
  38.  
  39. id             :: a -> a
  40. id    x         = x
  41.  
  42. curry          :: ((a,b) -> c) -> a -> b -> c
  43. curry f a b     =  f (a,b)
  44.  
  45. uncurry        :: (a -> b -> c) -> (a,b) -> c
  46. uncurry f (a,b) = f a b
  47.  
  48. fst            :: (a,b) -> a
  49. fst (x,_)       = x
  50.  
  51. snd            :: (a,b) -> b
  52. snd (_,y)       = y
  53.  
  54. fst3           :: (a,b,c) -> a
  55. fst3 (x,_,_)    = x
  56.  
  57. snd3           :: (a,b,c) -> b
  58. snd3 (_,x,_)    = x
  59.  
  60. thd3           :: (a,b,c) -> c
  61. thd3 (_,_,x)    = x
  62.  
  63. (.)            :: (b -> c) -> (a -> b) -> (a -> c)
  64. (f . g) x       = f (g x)
  65.  
  66. flip           :: (a -> b -> c) -> b -> a -> c
  67. flip  f x y     = f y x
  68.  
  69. ($)            :: (a -> b) -> a -> b     -- pronounced as `apply' elsewhere
  70. f $ x           = f x
  71.  
  72. while          :: (a -> Bool) -> (a -> a) -> a -> a
  73. while p f x | p x       = while p f (f x)
  74.             | otherwise = x
  75.  
  76. -- Boolean functions: -----------------------------------------------------
  77.  
  78. (&&), (||)     :: Bool -> Bool -> Bool
  79. False && x      = False
  80. True  && x      = x
  81.  
  82. False || x      = x
  83. True  || x      = True
  84.  
  85. not            :: Bool -> Bool
  86. not True        = False
  87. not False       = True
  88.  
  89. and, or        :: [Bool] -> Bool
  90. and             = foldr (&&) True
  91. or              = foldr (||) False
  92.  
  93. any, all       :: (a -> Bool) -> [a] -> Bool
  94. any p           = or  . map p
  95. all p           = and . map p
  96.  
  97. otherwise      :: Bool
  98. otherwise       = True
  99.  
  100. -- Character functions: ---------------------------------------------------
  101.  
  102. primitive ord "primCharToInt" :: Char -> Int
  103. primitive chr "primIntToChar" :: Int -> Char
  104.  
  105. isAscii, isControl, isPrint, isSpace            :: Char -> Bool
  106. isUpper, isLower, isAlpha, isDigit, isAlphanum  :: Char -> Bool
  107.  
  108. isAscii c     =  ord c < 128
  109.  
  110. isControl c   =  c < ' '    ||  c == '\DEL'
  111.  
  112. isPrint c     =  c >= ' '   &&  c <= '~'
  113.  
  114. isSpace c     =  c == ' '   || c == '\t'  || c == '\n'  || c == '\r'  ||
  115.                                c == '\f'  || c == '\v'
  116.  
  117. isUpper c     =  c >= 'A'   &&  c <= 'Z'
  118. isLower c     =  c >= 'a'   &&  c <= 'z'
  119.  
  120. isAlpha c     =  isUpper c  ||  isLower c
  121. isDigit c     =  c >= '0'   &&  c <= '9'
  122. isAlphanum c  =  isAlpha c  ||  isDigit c
  123.  
  124.  
  125. toUpper, toLower      :: Char -> Char
  126.  
  127. toUpper c | isLower c  = chr (ord c - ord 'a' + ord 'A')
  128.           | otherwise  = c
  129.  
  130. toLower c | isUpper c  = chr (ord c - ord 'A' + ord 'a')
  131.           | otherwise  = c
  132.  
  133. minChar, maxChar      :: Char
  134. minChar                = chr 0
  135. maxChar                = chr 255
  136.  
  137. -- Standard type classes: -------------------------------------------------
  138.  
  139. class Eq a where
  140.     (==), (/=) :: a -> a -> Bool
  141.     x /= y      = not (x == y)
  142.  
  143. class Eq a => Ord a where
  144.     (<), (<=), (>), (>=) :: a -> a -> Bool
  145.     max, min             :: a -> a -> a
  146.  
  147.     x <  y            = x <= y && x /= y
  148.     x >= y            = y <= x
  149.     x >  y            = y < x
  150.  
  151.     max x y | x >= y  = x
  152.             | y >= x  = y
  153.     min x y | x <= y  = x
  154.             | y <= x  = y
  155.  
  156. class Ord a => Ix a where
  157.     range   :: (a,a) -> [a]
  158.     index   :: (a,a) -> a -> Int
  159.     inRange :: (a,a) -> a -> Bool
  160.  
  161. class Ord a => Enum a where
  162.     enumFrom       :: a -> [a]              -- [n..]
  163.     enumFromThen   :: a -> a -> [a]         -- [n,m..]
  164.     enumFromTo     :: a -> a -> [a]         -- [n..m]
  165.     enumFromThenTo :: a -> a -> a -> [a]    -- [n,n'..m]
  166.  
  167.     enumFromTo n m        = takeWhile (m>=) (enumFrom n)
  168.     enumFromThenTo n n' m = takeWhile ((if n'>=n then (>=) else (<=)) m)
  169.                                       (enumFromThen n n')
  170.  
  171. class (Eq a, Text a, Add a, Mult a) => Num a where
  172.                                       -- simplified numeric class
  173.     (/) :: a -> a -> a
  174.     fromInteger        :: Int -> a
  175.  
  176. -- My type classes -------------------------------------------------
  177.  
  178. class LeftMul a b where
  179.     (*) :: a -> b -> b
  180.  
  181. class LeftMul a a => Mult a where
  182.      one      :: a
  183.      (^)      :: a -> Int -> a
  184.      product  :: [a] -> a
  185.      products :: [a] -> [a]
  186.      x ^ 0     = one
  187.      x ^ (2*n) = xx ^ n where xx = x*x
  188.      x ^ (n+1) = x*(x^n)
  189.      product   = foldl' (*) one
  190.      products  = scanl (*) one
  191.  
  192. class Add a where
  193.      (+),(-) :: a -> a -> a
  194.      negate  :: a -> a
  195.      nought  :: a
  196.      sum     :: [a] -> a
  197.      sums    :: [a] -> [a]
  198.      negate x = nought - x
  199.      sum      = foldl' (+) nought
  200.      sums     = scanl (+) nought
  201.  
  202. -- Type class instances: --------------------------------------------------
  203.  
  204. primitive primEqInt    "primEqInt",
  205.           primLeInt    "primLeInt"   :: Int -> Int -> Bool
  206. primitive primPlusInt  "primPlusInt",
  207.           primMinusInt "primMinusInt",
  208.           primDivInt   "primDivInt",
  209.           primMulInt   "primMulInt"  :: Int -> Int -> Int
  210. primitive primNegInt   "primNegInt"  :: Int -> Int
  211.  
  212. instance Eq ()  where () == () = True
  213. instance Ord () where () <= () = True
  214.  
  215. instance Eq Int  where (==) = primEqInt
  216.  
  217. instance Ord Int where (<=) = primLeInt
  218.  
  219. instance Ix Int where
  220.     range (m,n)      = [m..n]
  221.     index (m,n) i    = i - m
  222.     inRange (m,n) i  = m <= i && i <= n
  223.  
  224. instance Enum Int where
  225.     enumFrom n       = iterate (1+) n
  226.     enumFromThen n m = iterate ((m-n)+) n
  227. {-
  228. instance Num Int where
  229.     (+)           = primPlusInt
  230.     (-)           = primMinusInt
  231.     (*)           = primMulInt
  232.     (/)           = primDivInt
  233.     negate        = primNegInt
  234.     fromInteger x = x
  235. -}
  236. {- PC version off -}
  237. primitive primEqFloat    "primEqFloat",
  238.           primLeFloat    "primLeFloat"    :: Float -> Float -> Bool
  239. primitive primPlusFloat  "primPlusFloat", 
  240.           primMinusFloat "primMinusFloat", 
  241.           primDivFloat   "primDivFloat",
  242.           primMulFloat   "primMulFloat"   :: Float -> Float -> Float 
  243. primitive primNegFloat   "primNegFloat"   :: Float -> Float
  244. primitive primIntToFloat "primIntToFloat" :: Int -> Float
  245.  
  246. instance Eq Float where (==) = primEqFloat
  247.  
  248. instance Ord Float where (<=) = primLeFloat
  249.  
  250. instance Enum Float where
  251.     enumFrom n       = iterate (1.0+) n
  252.     enumFromThen n m = iterate ((m-n)+) n
  253. {-
  254. instance Num Float where
  255.     (+)         = primPlusFloat
  256.     (-)         = primMinusFloat
  257.     (*)         = primMulFloat
  258.     (/)         = primDivFloat 
  259.     negate      = primNegFloat
  260.     fromInteger = primIntToFloat
  261. -}
  262. primitive sin "primSinFloat",  asin  "primAsinFloat",
  263.           cos "primCosFloat",  acos  "primAcosFloat",
  264.           tan "primTanFloat",  atan  "primAtanFloat",
  265.           log "primLogFloat",  log10 "primLog10Float",
  266.           exp "primExpFloat",  sqrt  "primSqrtFloat" :: Float -> Float
  267. primitive atan2    "primAtan2Float" :: Float -> Float -> Float
  268. primitive truncate "primFloatToInt" :: Float -> Int
  269.  
  270. pi :: Float
  271. pi  = 3.1415926535
  272.  
  273. {- PC version on -}
  274.  
  275. primitive primEqChar   "primEqChar",
  276.           primLeChar   "primLeChar"  :: Char -> Char -> Bool
  277.  
  278. instance Eq Char  where (==) = primEqChar   -- c == d  =  ord c == ord d
  279.  
  280. instance Ord Char where (<=) = primLeChar   -- c <= d  =  ord c <= ord d
  281.  
  282. instance Ix Char where
  283.     range (c,c')      = [c..c']
  284.     index (c,c') ci   = ord ci - ord c
  285.     inRange (c,c') ci = ord c <= i && i <= ord c' where i = ord ci
  286.  
  287. instance Enum Char where
  288.     enumFrom c        = map chr [ord c .. ord maxChar]
  289.     enumFromThen c c' = map chr [ord c, ord c' .. ord lastChar]
  290.                       where lastChar = if c' < c then minChar else maxChar
  291.  
  292. instance Eq a => Eq [a] where
  293.     []     == []     =  True
  294.     []     == (y:ys) =  False
  295.     (x:xs) == []     =  False
  296.     (x:xs) == (y:ys) =  x==y && xs==ys
  297.  
  298. instance Ord a => Ord [a] where
  299.     []     <= _      =  True
  300.     (_:_)  <= []     =  False
  301.     (x:xs) <= (y:ys) =  x<y || (x==y && xs<=ys)
  302.  
  303. instance (Eq a, Eq b) => Eq (a,b) where
  304.     (x,y) == (u,v)  =  x==u && y==v
  305.  
  306. instance (Ord a, Ord b) => Ord (a,b) where
  307.     (x,y) <= (u,v)  = x<u  ||  (x==u && y<=v)
  308.  
  309. instance Eq Bool where
  310.     True  == True   =  True
  311.     False == False  =  True
  312.     _     == _      =  False
  313.  
  314. instance Ord Bool where
  315.     False <= x      = True
  316.     True  <= x      = x
  317.  
  318. -- my instances --------------------------------------------------------
  319.  
  320. instance LeftMul Int Int where
  321.    (*) = primMulInt
  322.  
  323. instance LeftMul Int Float where
  324.    (*)  = primMulFloat.primIntToFloat
  325.  
  326. instance LeftMul Float Float where
  327.    (*)  = primMulFloat
  328.  
  329. instance (LeftMul a b, LeftMul a c) => LeftMul a (b,c)
  330.    where a * (b,c) = (a*b, a*c)
  331.  
  332. instance (LeftMul a b, LeftMul a c, LeftMul a d) => LeftMul a (b,c,d)
  333.     where  a * (b,c,d) = (a*b, a*c, a*d)
  334.  
  335. instance Mult Int 
  336.     where  one = 1
  337.  
  338. instance Mult Float
  339.     where  one = 1.0
  340.  
  341. instance Add Int
  342.     where (+)    = primPlusInt
  343.           (-)    = primMinusInt
  344.           negate = primNegInt
  345.           nought = 0
  346.  
  347. instance Add Float
  348.     where (+)    = primPlusFloat
  349.           (-)    = primMinusFloat
  350.           negate = primNegFloat
  351.           nought = 0.0
  352.  
  353. instance (Add a, Add b) => Add (a,b)
  354.     where  (a,b) + (a',b') = (a+a',b+b')
  355.            (a,b) - (a',b') = (a-a',b-b')
  356.            negate (a,b)    = (-a,-b)
  357.            nought          = (nought,nought)
  358.  
  359. instance (Add a, Add b, Add c) => Add (a,b,c)
  360.      where (a,b,c) + (a',b',c') = (a+a',b+b',c+c')
  361.            (a,b,c) - (a',b',c') = (a-a',b-b',c-c')
  362.            negate (a,b,c)       = (-a,-b,-c)
  363.            nought               = (nought,nought,nought)
  364.  
  365. instance Add a => Add (b->a)
  366.      where f + f' = \b -> (f b)+(f' b)
  367.            f - f' = \b -> (f b)-(f' b)
  368.            - f    = \b -> -(f b)
  369.            nought = \b -> nought
  370.  
  371. instance Num Int
  372.      where (/)           = primDivInt
  373.            fromInteger x = x
  374.  
  375. instance Num Float
  376.       where (/)          = primDivFloat
  377.             fromInteger  = primIntToFloat
  378.  
  379. -- Standard numerical functions: ------------------------------------------
  380.  
  381. primitive div    "primDivInt",
  382.           quot   "primQuotInt",
  383.           rem    "primRemInt",
  384.           mod    "primModInt"    :: Int -> Int -> Int
  385.  
  386. subtract  :: Add a => a -> a -> a
  387. subtract   = flip (-)
  388.  
  389. even, odd :: Int -> Bool
  390. even x     = x `rem` 2 == 0
  391. odd        = not . even
  392.  
  393. gcd       :: Int -> Int -> Int
  394. gcd x y    = gcd' (abs x) (abs y)
  395.              where gcd' x 0 = x
  396.                    gcd' x y = gcd' y (x `rem` y)
  397.  
  398. hcf = gcd
  399.  
  400. lcm       :: Int -> Int -> Int
  401. lcm _ 0    = 0
  402. lcm 0 _    = 0
  403. lcm x y    = abs ((x `quot` gcd x y) * y)
  404.  
  405. {-
  406. (^)       :: Num a => a -> Int -> a
  407. x ^ 0      = fromInteger 1
  408. x ^ (n+1)  = f x n x
  409.              where f _ 0 y = y
  410.                    f x n y = g x n where
  411.                              g x n | even n    = g (x*x) (n`quot`2)
  412.                                    | otherwise = f x (n-1) (x*y)
  413. -}
  414.  
  415. abs                     :: (Add a, Ord a) => a -> a
  416. abs x | x>=nought        = x
  417.       | otherwise        = -x
  418.  
  419. signum                  :: (Add a, Ord a) => a -> Int
  420. signum x
  421.       | x==nought        = 0
  422.       | x> nought        = 1
  423.       | otherwise        = -1
  424. {- 
  425. sum, product    :: Num a => [a] -> a
  426. sum              = foldl' (+) (fromInteger 0)
  427. product          = foldl' (*) (fromInteger 1)
  428.  
  429. sums, products  :: Num a => [a] -> [a]
  430. sums             = scanl (+) (fromInteger 0)
  431. products         = scanl (*) (fromInteger 1)
  432. -}
  433.  
  434. -- Constructor classes: ---------------------------------------------------
  435.  
  436. class Functor f where
  437.     map :: (a -> b) -> (f a -> f b)
  438.  
  439. class Functor m => Monad m where
  440.     result    :: a -> m a
  441.     join      :: m (m a) -> m a
  442.     bind      :: m a -> (a -> m b) -> m b
  443.  
  444.     join x     = bind x id
  445.     x `bind` f = join (map f x)
  446.  
  447. class Monad m => Monad0 m where
  448.     zero   :: m a
  449.  
  450. class Monad0 c => MonadPlus c where
  451.     (++) :: c a -> c a -> c a
  452.  
  453. class (Functor left, Functor right) => Adjoint left right where
  454.     univ    :: (a -> right b) -> (left a -> b)
  455.     unit    :: a -> right (left a)
  456.     couniv  :: (left a -> b) -> (a -> right b)
  457.     counit  :: left (right a) -> a
  458.  
  459.     unit     = couniv id
  460.     counit   = univ id
  461.     univ g   = counit . map g
  462.     couniv g = map g . unit
  463.  
  464. -- Monad based utilities: -------------------------------------------------
  465.  
  466. apply            :: Monad m => (a -> m b) -> (m a -> m b)
  467. apply             = flip bind
  468.  
  469. (@@)             :: Monad m => (a -> m b) -> (c -> m a) -> (c -> m b)
  470. f @@ g            = join . map f . g
  471.  
  472. concat           :: MonadPlus c => [c a] -> c a
  473. concat            = foldr (++) zero
  474.  
  475. filter           :: Monad0 m => (a -> Bool) -> m a -> m a
  476. filter p xs       = [ x | x<-xs, p x ]
  477.  
  478. mfoldl           :: Monad m => (a -> b -> m a) -> a -> [b] -> m a
  479. mfoldl f a []     = result a
  480. mfoldl f a (x:xs) = f a x `bind` (\fax -> mfoldl f fax xs)
  481.  
  482. mfoldr           :: Monad m => (a -> b -> m b) -> b -> [a] -> m b
  483. mfoldr f a []     = result a
  484. mfoldr f a (x:xs) = mfoldr f a xs `bind` (\y -> f x y)
  485.  
  486. mapl             :: Monad m => (a -> m b) -> ([a] -> m [b])
  487. mapl f []         = [ [] ]
  488. mapl f (x:xs)     = [ y:ys | y <- f x, ys <- mapl f xs ]
  489.  
  490. mapr             :: Monad m => (a -> m b) -> ([a] -> m [b])
  491. mapr f []         = [ [] ]
  492. mapr f (x:xs)     = [ y:ys | ys <- mapr f xs, y <- f x ]
  493.  
  494. -- The monad of lists: ----------------------------------------------------
  495.  
  496. instance Functor   [] where map f []     = []
  497.                             map f (x:xs) = f x : map f xs
  498.  
  499. instance Monad     [] where result x        = [x]
  500.                             []     `bind` f = []
  501.                             (x:xs) `bind` f = f x ++ (xs `bind` f)
  502.  
  503. instance Monad0    [] where zero         = []
  504.  
  505. instance MonadPlus [] where []     ++ ys = ys
  506.                             (x:xs) ++ ys = x : (xs ++ ys)
  507.  
  508. -- Standard list processing functions: ------------------------------------
  509.  
  510. head             :: [a] -> a
  511. head (x:_)        = x
  512.  
  513. last             :: [a] -> a
  514. last [x]          = x
  515. last (_:xs)       = last xs
  516.  
  517. tail             :: [a] -> [a]
  518. tail (_:xs)       = xs
  519.  
  520. init             :: [a] -> [a]
  521. init [x]          = []
  522. init (x:xs)       = x : init xs
  523.  
  524. genericLength    :: Num a => [b] -> a    -- calculate length of list
  525. genericLength     = foldl' (\n _ -> n + fromInteger 1) (fromInteger 0)
  526.  
  527. length           :: [a] -> Int
  528. length            = foldl' (\n _ -> n + 1) 0
  529.  
  530. (!!)             :: [a] -> Int -> a    -- xs!!n selects the nth element of
  531. (x:_)  !! 0       = x                  -- the list xs (first element xs!!0)
  532. (_:xs) !! (n+1)   = xs !! n              -- for any n < length xs.
  533.  
  534. iterate          :: (a -> a) -> a -> [a] -- generate the infinite list
  535. iterate f x       = x : iterate f (f x)  -- [x, f x, f (f x), ...
  536.  
  537. repeat           :: a -> [a]             -- generate the infinite list
  538. repeat x          = xs where xs = x:xs   -- [x, x, x, x, ...
  539.  
  540. cycle            :: [a] -> [a]           -- generate the infinite list
  541. cycle xs          = xs' where xs'=xs++xs'-- xs ++ xs ++ xs ++ ...
  542.  
  543. copy             :: Int -> a -> [a]      -- make list of n copies of x
  544. copy n x          = take n xs where xs = x:xs
  545.  
  546. nub              :: Eq a => [a] -> [a]   -- remove duplicates from list
  547. nub []            = []
  548. nub (x:xs)        = x : nub (filter (x/=) xs)
  549.  
  550. reverse          :: [a] -> [a]           -- reverse elements of list
  551. reverse           = foldl (flip (:)) []
  552.  
  553. elem, notElem    :: Eq a => a -> [a] -> Bool
  554. elem              = any . (==)           -- test for membership in list
  555. notElem           = all . (/=)           -- test for non-membership
  556.  
  557. maximum, minimum :: Ord a => [a] -> a
  558. maximum           = foldl1 max          -- max element in non-empty list
  559. minimum           = foldl1 min          -- min element in non-empty list
  560.  
  561. transpose        :: [[a]] -> [[a]]      -- transpose list of lists
  562. transpose         = foldr
  563.                       (\xs xss -> zipWith (:) xs (xss ++ repeat []))
  564.                       []
  565.  
  566. -- null provides a simple and efficient way of determining whether a given
  567. -- list is empty, without using (==) and hence avoiding a constraint of the
  568. -- form Eq [a].
  569.  
  570. null             :: [a] -> Bool
  571. null []           = True
  572. null (_:_)        = False
  573.  
  574. -- (\\) is used to remove the first occurrence of each element in the 
  575. -- second list from the first list.  It is a kind of inverse of (++) in 
  576. -- the sense that  (xs ++ ys) \\ xs = ys for any finite list xs of 
  577. -- proper values xs.
  578.  
  579. (\\)             :: Eq a => [a] -> [a] -> [a]
  580. (\\)              = foldl del
  581.                     where []     `del` _  = []
  582.                           (x:xs) `del` y
  583.                              | x == y     = xs
  584.                              | otherwise  = x : xs `del` y
  585.  
  586. -- Fold primitives:  The foldl and scanl functions, variants foldl1 and
  587. -- scanl1 for non-empty lists, and strict variants foldl' scanl' describe
  588. -- common patterns of recursion over lists.  Informally:
  589. --
  590. --  foldl f a [x1, x2, ..., xn]  = f (...(f (f a x1) x2)...) xn
  591. --                               = (...((a `f` x1) `f` x2)...) `f` xn
  592. -- etc...
  593. --
  594. -- The functions foldr, scanr and variants foldr1, scanr1 are duals of 
  595. -- these functions:
  596. -- e.g.  foldr f a xs = foldl (flip f) a (reverse xs)  for finite lists xs.
  597.  
  598. foldl            :: (a -> b -> a) -> a -> [b] -> a
  599. foldl f z []      = z
  600. foldl f z (x:xs)  = foldl f (f z x) xs
  601.  
  602. foldl1           :: (a -> a -> a) -> [a] -> a
  603. foldl1 f (x:xs)   = foldl f x xs
  604.  
  605. foldl'           :: (a -> b -> a) -> a -> [b] -> a
  606. foldl' f a []     =  a
  607. foldl' f a (x:xs) =  strict (foldl' f) (f a x) xs
  608.  
  609. scanl            :: (a -> b -> a) -> a -> [b] -> [a]
  610. scanl f q xs      = q : (case xs of
  611.                          []   -> []
  612.                          x:xs -> scanl f (f q x) xs)
  613.  
  614. scanl1           :: (a -> a -> a) -> [a] -> [a]
  615. scanl1 f (x:xs)   = scanl f x xs
  616.  
  617. scanl'           :: (a -> b -> a) -> a -> [b] -> [a]
  618. scanl' f q xs     = q : (case xs of
  619.                          []   -> []
  620.                          x:xs -> strict (scanl' f) (f q x) xs)
  621.  
  622. foldr            :: (a -> b -> b) -> b -> [a] -> b
  623. foldr f z []      = z
  624. foldr f z (x:xs)  = f x (foldr f z xs)
  625.  
  626. foldr1           :: (a -> a -> a) -> [a] -> a
  627. foldr1 f [x]      = x
  628. foldr1 f (x:xs)   = f x (foldr1 f xs)
  629.  
  630. scanr            :: (a -> b -> b) -> b -> [a] -> [b]
  631. scanr f q0 []     = [q0]
  632. scanr f q0 (x:xs) = f x q : qs
  633.                     where qs@(q:_) = scanr f q0 xs
  634.  
  635. scanr1           :: (a -> a -> a) -> [a] -> [a]
  636. scanr1 f [x]      = [x]
  637. scanr1 f (x:xs)   = f x q : qs
  638.                     where qs@(q:_) = scanr1 f xs
  639.  
  640. -- List breaking functions:
  641. --
  642. --   take n xs       returns the first n elements of xs
  643. --   drop n xs       returns the remaining elements of xs
  644. --   splitAt n xs    = (take n xs, drop n xs)
  645. --
  646. --   takeWhile p xs  returns the longest initial segment of xs whose
  647. --                   elements satisfy p
  648. --   dropWhile p xs  returns the remaining portion of the list
  649. --   span p xs       = (takeWhile p xs, dropWhile p xs)
  650. --
  651. --   takeUntil p xs  returns the list of elements upto and including the
  652. --                   first element of xs which satisfies p
  653.  
  654. take                :: Int -> [a] -> [a]
  655. take 0     _         = []
  656. take _     []        = []
  657. take (n+1) (x:xs)    = x : take n xs
  658.  
  659. drop                :: Int -> [a] -> [a]
  660. drop 0     xs        = xs
  661. drop _     []        = []
  662. drop (n+1) (_:xs)    = drop n xs
  663.  
  664. splitAt             :: Int -> [a] -> ([a], [a])
  665. splitAt 0     xs     = ([],xs)
  666. splitAt _     []     = ([],[])
  667. splitAt (n+1) (x:xs) = (x:xs',xs'') where (xs',xs'') = splitAt n xs
  668.  
  669. takeWhile           :: (a -> Bool) -> [a] -> [a]
  670. takeWhile p []       = []
  671. takeWhile p (x:xs)
  672.          | p x       = x : takeWhile p xs
  673.          | otherwise = []
  674.  
  675. takeUntil           :: (a -> Bool) -> [a] -> [a]
  676. takeUntil p []       = []
  677. takeUntil p (x:xs)
  678.        | p x         = [x]
  679.        | otherwise   = x : takeUntil p xs
  680.  
  681. dropWhile           :: (a -> Bool) -> [a] -> [a]
  682. dropWhile p []       = []
  683. dropWhile p xs@(x:xs')
  684.          | p x       = dropWhile p xs'
  685.          | otherwise = xs
  686.  
  687. span, break         :: (a -> Bool) -> [a] -> ([a],[a])
  688. span p []            = ([],[])
  689. span p xs@(x:xs')
  690.          | p x       = let (ys,zs) = span p xs' in (x:ys,zs)
  691.          | otherwise = ([],xs)
  692. break p              = span (not . p)
  693.  
  694. -- Text processing:
  695. --   lines s     returns the list of lines in the string s.
  696. --   words s     returns the list of words in the string s.
  697. --   unlines ls  joins the list of lines ls into a single string
  698. --               with lines separated by newline characters.
  699. --   unwords ws  joins the list of words ws into a single string
  700. --               with words separated by spaces.
  701.  
  702. lines     :: String -> [String]
  703. lines ""   = []
  704. lines s    = l : (if null s' then [] else lines (tail s'))
  705.              where (l, s') = break ('\n'==) s
  706.  
  707. words     :: String -> [String]
  708. words s    = case dropWhile isSpace s of
  709.                   "" -> []
  710.                   s' -> w : words s''
  711.                         where (w,s'') = break isSpace s'
  712.  
  713. unlines   :: [String] -> String
  714. unlines    = concat . map (\l -> l ++ "\n")
  715.  
  716. unwords   :: [String] -> String
  717. unwords [] = []
  718. unwords ws = foldr1 (\w s -> w ++ ' ':s) ws
  719.  
  720. -- Merging and sorting lists:
  721.  
  722. merge               :: Ord a => [a] -> [a] -> [a] 
  723. merge []     ys      = ys
  724. merge xs     []      = xs
  725. merge (x:xs) (y:ys)
  726.         | x <= y     = x : merge xs (y:ys)
  727.         | otherwise  = y : merge (x:xs) ys
  728.  
  729. sort                :: Ord a => [a] -> [a]
  730. sort                 = foldr insert []
  731.  
  732. insert              :: Ord a => a -> [a] -> [a]
  733. insert x []          = [x]
  734. insert x (y:ys)
  735.         | x <= y     = x:y:ys
  736.         | otherwise  = y:insert x ys
  737.  
  738. qsort               :: Ord a => [a] -> [a]
  739. qsort []             = []
  740. qsort (x:xs)         = qsort [ u | u<-xs, u<x ] ++
  741.                              [ x ] ++
  742.                        qsort [ u | u<-xs, u>=x ]
  743.  
  744. -- zip and zipWith families of functions:
  745.  
  746. zip  :: [a] -> [b] -> [(a,b)]
  747. zip   = zipWith  (\a b -> (a,b))
  748.  
  749. zip3 :: [a] -> [b] -> [c] -> [(a,b,c)]
  750. zip3  = zipWith3 (\a b c -> (a,b,c))
  751.  
  752. zip4 :: [a] -> [b] -> [c] -> [d] -> [(a,b,c,d)]
  753. zip4  = zipWith4 (\a b c d -> (a,b,c,d))
  754.  
  755. zip5 :: [a] -> [b] -> [c] -> [d] -> [e] -> [(a,b,c,d,e)]
  756. zip5  = zipWith5 (\a b c d e -> (a,b,c,d,e))
  757.  
  758. zip6 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [(a,b,c,d,e,f)]
  759. zip6  = zipWith6 (\a b c d e f -> (a,b,c,d,e,f))
  760.  
  761. zip7 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [(a,b,c,d,e,f,g)]
  762. zip7  = zipWith7 (\a b c d e f g -> (a,b,c,d,e,f,g))
  763.  
  764.  
  765. zipWith                  :: (a->b->c) -> [a]->[b]->[c]
  766. zipWith z (a:as) (b:bs)   = z a b : zipWith z as bs
  767. zipWith _ _      _        = []
  768.  
  769. zipWith3                 :: (a->b->c->d) -> [a]->[b]->[c]->[d]
  770. zipWith3 z (a:as) (b:bs) (c:cs)
  771.                           = z a b c : zipWith3 z as bs cs
  772. zipWith3 _ _ _ _          = []
  773.  
  774. zipWith4                 :: (a->b->c->d->e) -> [a]->[b]->[c]->[d]->[e]
  775. zipWith4 z (a:as) (b:bs) (c:cs) (d:ds)
  776.                           = z a b c d : zipWith4 z as bs cs ds
  777. zipWith4 _ _ _ _ _        = []
  778.  
  779. zipWith5              :: (a->b->c->d->e->f) -> [a]->[b]->[c]->[d]->[e]->[f]
  780. zipWith5 z (a:as) (b:bs) (c:cs) (d:ds) (e:es)
  781.                           = z a b c d e : zipWith5 z as bs cs ds es
  782. zipWith5 _ _ _ _ _ _      = []
  783.  
  784. zipWith6                 :: (a->b->c->d->e->f->g)
  785.                             -> [a]->[b]->[c]->[d]->[e]->[f]->[g]
  786. zipWith6 z (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs)
  787.                           = z a b c d e f : zipWith6 z as bs cs ds es fs
  788. zipWith6 _ _ _ _ _ _ _    = []
  789.  
  790. zipWith7                 :: (a->b->c->d->e->f->g->h)
  791.                              -> [a]->[b]->[c]->[d]->[e]->[f]->[g]->[h]
  792. zipWith7 z (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs) (g:gs)
  793.                        = z a b c d e f g : zipWith7 z as bs cs ds es fs gs
  794. zipWith7 _ _ _ _ _ _ _ _  = []
  795.  
  796. unzip                    :: [(a,b)] -> ([a],[b])
  797. unzip                   = foldr (\(a,b) ~(as,bs) -> (a:as, b:bs)) ([], [])
  798.  
  799. -- Formatted output: ------------------------------------------------------
  800.  
  801. primitive primPrint "primPrint"  :: Int -> a -> String -> String
  802.  
  803. show'       :: a -> String
  804. show' x      = primPrint 0 x []
  805.  
  806. cjustify, ljustify, rjustify :: Int -> String -> String
  807.  
  808. cjustify n s = space halfm ++ s ++ space (m - halfm)
  809.                where m     = n - length s
  810.                      halfm = m `div` 2
  811. ljustify n s = s ++ space (n - length s)
  812. rjustify n s = space (n - length s) ++ s
  813.  
  814. space       :: Int -> String
  815. space n      = copy n ' '
  816.  
  817. layn        :: [String] -> String
  818. layn         = lay 1 where lay _ []     = []
  819.                            lay n (x:xs) = rjustify 4 (show n) ++ ") "
  820.                                            ++ x ++ "\n" ++ lay (n+1) xs
  821.  
  822. -- Miscellaneous: ---------------------------------------------------------
  823.  
  824. until                  :: (a -> Bool) -> (a -> a) -> a -> a
  825. until p f x | p x       = x
  826.             | otherwise = until p f (f x)
  827.  
  828. until'                 :: (a -> Bool) -> (a -> a) -> a -> [a]
  829. until' p f              = takeUntil p . iterate f
  830.  
  831. primitive error "primError" :: String -> a
  832.  
  833. undefined              :: a
  834. undefined | False       = undefined
  835.  
  836. asTypeOf               :: a -> a -> a
  837. x `asTypeOf` _          = x
  838.  
  839. -- A trimmed down version of the Haskell Text class: ---------------------
  840.  
  841. type  ShowS   = String -> String
  842.  
  843. class Text a where 
  844.     showsPrec      :: Int -> a -> ShowS
  845.     showList       :: [a] -> ShowS
  846.  
  847.     showsPrec       = primPrint
  848.     showList []     = showString "[]"
  849.     showList (x:xs) = showChar '[' . shows x . showl xs
  850.                     where showl []     = showChar ']'
  851.                           showl (x:xs) = showChar ',' . shows x . showl xs
  852.  
  853. shows      :: Text a => a -> ShowS
  854. shows       = showsPrec 0
  855.  
  856. show       :: Text a => a -> String
  857. show x      = shows x ""
  858.  
  859. showChar   :: Char -> ShowS
  860. showChar    = (:)
  861.  
  862. showString :: String -> ShowS
  863. showString  = (++)
  864.  
  865. instance Text () where
  866.     showsPrec d ()    = showString "()"
  867.  
  868. instance Text Bool where
  869.     showsPrec d True  = showString "True"
  870.     showsPrec d False = showString "False"
  871.  
  872. primitive primShowsInt "primShowsInt" :: Int -> Int -> String -> String
  873. instance Text Int where showsPrec = primShowsInt
  874.  
  875. {- PC version off -}
  876. primitive primShowsFloat "primShowsFloat" :: 
  877.                      Int -> Float -> String -> String
  878. instance Text Float where showsPrec = primShowsFloat
  879. {- PC version on -}
  880.  
  881. instance Text Char where
  882.     showsPrec p c = showString [q, c, q] where q = '\''
  883.     showList cs   = showChar '"' . showl cs
  884.                     where showl ""       = showChar '"'
  885.                           showl ('"':cs) = showString "\\\"" . showl cs
  886.                           showl (c:cs)   = showChar c . showl cs
  887.                           -- Haskell has   showLitChar c . showl cs
  888.  
  889. instance Text a => Text [a]  where
  890.     showsPrec p = showList
  891.  
  892. instance (Text a, Text b) => Text (a,b) where
  893.     showsPrec p (x,y) = showChar '(' . shows x . showChar ',' .
  894.                                        shows y . showChar ')'
  895.  
  896. -- I/O functions and definitions: -----------------------------------------
  897.  
  898. stdin         =  "stdin"
  899. stdout        =  "stdout"
  900. stderr        =  "stderr"
  901. stdecho       =  "stdecho"
  902.  
  903. {- The Dialogue, Request, Response and IOError datatypes are now builtin:
  904. data Request  =  -- file system requests:
  905.                 ReadFile      String         
  906.               | WriteFile     String String
  907.               | AppendFile    String String
  908.                  -- channel system requests:
  909.               | ReadChan      String 
  910.               | AppendChan    String String
  911.                  -- environment requests:
  912.               | Echo          Bool
  913.               | GetArgs
  914.               | GetProgName
  915.               | GetEnv        String
  916.  
  917. data Response = Success
  918.               | Str     String 
  919.               | Failure IOError
  920.               | StrList [String]
  921.  
  922. data IOError  = WriteError   String
  923.               | ReadError    String
  924.               | SearchError  String
  925.               | FormatError  String
  926.               | OtherError   String
  927.  
  928. type Dialogue    =  [Response] -> [Request]
  929. -}
  930.  
  931. type SuccCont    =                Dialogue
  932. type StrCont     =  String     -> Dialogue
  933. type StrListCont =  [String]   -> Dialogue
  934. type FailCont    =  IOError    -> Dialogue
  935.  
  936. done            ::                                                Dialogue
  937. readFile        :: String ->           FailCont -> StrCont     -> Dialogue
  938. writeFile       :: String -> String -> FailCont -> SuccCont    -> Dialogue
  939. appendFile      :: String -> String -> FailCont -> SuccCont    -> Dialogue
  940. readChan        :: String ->           FailCont -> StrCont     -> Dialogue
  941. appendChan      :: String -> String -> FailCont -> SuccCont    -> Dialogue
  942. echo            :: Bool ->             FailCont -> SuccCont    -> Dialogue
  943. getArgs         ::                     FailCont -> StrListCont -> Dialogue
  944. getProgName     ::                     FailCont -> StrCont     -> Dialogue
  945. getEnv          :: String ->           FailCont -> StrCont     -> Dialogue
  946.  
  947. done resps    =  []
  948. readFile name fail succ resps =
  949.      (ReadFile name) : strDispatch fail succ resps
  950. writeFile name contents fail succ resps =
  951.     (WriteFile name contents) : succDispatch fail succ resps
  952. appendFile name contents fail succ resps =
  953.     (AppendFile name contents) : succDispatch fail succ resps
  954. readChan name fail succ resps =
  955.     (ReadChan name) : strDispatch fail succ resps
  956. appendChan name contents fail succ resps =
  957.     (AppendChan name contents) : succDispatch fail succ resps
  958. echo bool fail succ resps =
  959.     (Echo bool) : succDispatch fail succ resps
  960. getArgs fail succ resps =
  961.     GetArgs : strListDispatch fail succ resps
  962. getProgName fail succ resps =
  963.     GetProgName : strDispatch fail succ resps
  964. getEnv name fail succ resps =
  965.     (GetEnv name) : strDispatch fail succ resps
  966.  
  967. strDispatch fail succ (resp:resps) = 
  968.             case resp of Str val     -> succ val resps
  969.                          Failure msg -> fail msg resps
  970.  
  971. succDispatch fail succ (resp:resps) = 
  972.             case resp of Success     -> succ resps
  973.                          Failure msg -> fail msg resps
  974.  
  975. strListDispatch fail succ (resp:resps) =
  976.             case resp of StrList val -> succ val resps
  977.                          Failure msg -> fail msg resps
  978.  
  979. abort           :: FailCont
  980. abort err        = done
  981.  
  982. exit            :: FailCont
  983. exit err         = appendChan stderr msg abort done
  984.                    where msg = case err of ReadError s   -> s
  985.                                            WriteError s  -> s
  986.                                            SearchError s -> s
  987.                                            FormatError s -> s
  988.                                            OtherError s  -> s
  989.  
  990. print           :: Text a => a -> Dialogue
  991. print x          = appendChan stdout (show x) exit done
  992.  
  993. prints          :: Text a => a -> String -> Dialogue
  994. prints x s       = appendChan stdout (shows x s) exit done
  995.  
  996. interact        :: (String -> String) -> Dialogue
  997. interact f       = readChan stdin exit
  998.                             (\x -> appendChan stdout (f x) exit done)
  999.  
  1000. run             :: (String -> String) -> Dialogue
  1001. run f            = echo False exit (interact f)
  1002.  
  1003. primitive primFopen "primFopen" :: String -> a -> (String -> a) -> a
  1004.  
  1005. openfile        :: String -> String
  1006. openfile f       = primFopen f (error ("can't open file "++f)) id
  1007.  
  1008. -- End of Gofer gcwprel prelude: -----------------------------------------
  1009.